<template >
  <div id="vditor" />
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch  } from 'vue';
import Vditor from 'vditor';
import 'vditor/dist/index.css';
import { FileResponse, open, save, ask } from "@tauri-apps/plugin-dialog"
import { writeTextFile, readTextFile, create, exists, BaseDirectory } from '@tauri-apps/plugin-fs';
import { resolve, appDataDir } from '@tauri-apps/api/path';

import * as event from "@tauri-apps/api/event";
import { createWin } from "../windows/actions.ts"
import Windows from "../windows/index.ts"

import { invoke } from "@tauri-apps/api/core";
import { convertFileSrc } from '@tauri-apps/api/core';
const emit = defineEmits(["addPath", "delPath", "clearFileId", "clearFilePath"])
import { autograph } from '../utils/index.ts'

const props = defineProps({
  userId: String,
  filePath: String,
  fileId: Number
})





console.log(props.userId)
const cacheFileName = 'file.txt';
const fileName = ref(cacheFileName);
const filePath = ref("");
const fileId = ref(0);
const fileContent = ref("");
const vditor = ref<Vditor | null>(null);


var url = window.location.href;
var reg=/[?&]([^?&#]+)=([^?&#]+)/g;
var param=reactive(new Map<string, string>());
var ret =  reg.exec(url);
while(ret){ // 当ret为null时表示已经匹配到最后了，直接跳出
  param.set(ret[1].toString(), ret[2].toString())
  ret = reg.exec(url);
}



event.listen("tauri://file-drop", async (e) => {
    let p:any = e.payload;
    console.log(p)
    console.log(p.paths)
    if (p.paths.length === 1) {
      if ((p.paths[0]+"").endsWith("md")) {
            console.log("==========" + p.paths[0])
            await openFile(p.paths[0])
            vditor.value!.clearStack();
      } else {
        let name = getFileName(p.paths[0])
        if (name.endsWith("jpg") || name.endsWith("png") || name.endsWith("JPG") || name.endsWith("PNG")) {
          vditor.value?.insertValue("![" + name + "](" + convertFileSrc(p.paths[0]) + ")")
        } else {
          vditor.value?.insertValue("[" + name + "](" + p.paths[0] + ")")
        }
      }
    } else {
      for (let i=0; i < p.paths.length; i++) {
        let name = getFileName(p.paths[i])
        if (name.endsWith("jpg") || name.endsWith("png") || name.endsWith("JPG") || name.endsWith("PNG")) {
          vditor.value?.insertValue("![" + name + "](" + convertFileSrc(p.paths[i]) + ")")
        } else {
          vditor.value?.insertValue("[" + name + "](" + p.paths[i] + ")")
        }
      }
    }

  });

event.listen("tauri://file-drop-hover", (e) => {
  console.log("Tauri event", e);
});

event.listen("tauri://file-drop-cancelled", (e) => {
  console.log("Tauri event", e);
});

event.listen("tauri://webview-created", (e) => {
  console.log("webview-created", e);
})



onMounted(async () => {

  //进入页面是否有参数
  if (param.get("target")) {
    var target = window.decodeURI(param.get("target")!);
    let path:string = "";
    if (param.get("source")) {
      if (target.startsWith("\\") || target.startsWith("./")) {
        path = await resolve(param.get("source")!, target.replace("\\", "").replace("./", ""));
      } else if (target.indexOf(":") === 1 || target.startsWith("/")) {
        path = target;
      }
    } else {
      path = target;
    }

    if (path) {
      openFile(path);
    }

  }


  const appDataDirPath = await appDataDir();
  const path = await resolve(appDataDirPath, '..', 'users', 'tauri', 'avatar.png');
  console.log(path)

  //const db = await Database.load('sqlite:test.db');
  new Windows().listen()


  //读取地址文件
  watch(() => props.filePath, async () => {
    console.log("有变化" + props.filePath)
      if (props.filePath) {
        let rest:string = await invoke("read_file", {path: props.filePath});
        //console.log("********" + rest);
          if (rest.indexOf("#@#error#@#_") > -1) {
            const answer = await ask("文件打开失败！是否移除？ \r\n 保留添加内容，会生成对应文件", {
              title: rest.replace("#@#error#@#_", ""),
              kind: "warning",
              okLabel:"移除",
              cancelLabel:"保留"
            });
            if (answer) {
              emit("delPath", props.filePath);
            }
            rest = "";
          }
        fileId.value = 0;
        fileContent.value = rest;
        filePath.value = getPath(props.filePath);
        fileName.value = getFileName(props.filePath);
        vditor.value?.setValue(fileContent.value);
        vditor.value!.clearStack();
      }
  })



  watch(() => props.fileId, async () => {
    console.log("有变化" + props.filePath)
      if (props.fileId && props.fileId != 0) {
        console.log("fileId++++++++" + props.fileId)
        let fileInfo:any = await invoke("get_file", {fileId: props.fileId, userId: "123456"});
        console.log("********" + JSON.stringify(fileInfo));
        fileId.value = props.fileId;
        fileContent.value = fileInfo.content;
        filePath.value = getPath(fileInfo.local_path);
        fileName.value = getFileName(fileInfo.local_path);
        vditor.value?.setValue(fileContent.value);
        vditor.value!.clearStack();
      }
  })


  if (!fileContent.value) {
    //判断默认文件是否存在
    const exit = await exists(cacheFileName, { baseDir: BaseDirectory.AppData });
    console.log(exit)
    if (!exit) {
      await create(cacheFileName, { baseDir: BaseDirectory.AppData })
      console.log("创建文件" + cacheFileName);
    }
    fileContent.value = await readTextFile(cacheFileName, { baseDir: BaseDirectory.AppData });
  }

  vditor.value = new Vditor('vditor', {
    height:window.innerHeight - 2,
    toolbar: [
    {
      name: 'new',
      tipPosition: 's',
      tip: '新建文件',
      className: 'right',
      icon: '<svg class="bi bi-file-plus" width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg"><path d="M9 1H4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V8h-1v5a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1h5V1z"/><path fill-rule="evenodd" d="M13.5 1a.5.5 0 0 1 .5.5v2a.5.5 0 0 1-.5.5h-2a.5.5 0 0 1 0-1H13V1.5a.5.5 0 0 1 .5-.5z"/><path fill-rule="evenodd" d="M13 3.5a.5.5 0 0 1 .5-.5h2a.5.5 0 0 1 0 1H14v1.5a.5.5 0 0 1-1 0v-2z"/></svg>',
      async click () {
        console.log(filePath.value)
        emit("clearFileId", 0);
        emit("clearFilePath", "");
        if (!filePath.value) {
          console.log(1)
          const answer = await ask("当前文件是否保存？", {
            title: "提示",
            kind: "warning",
            okLabel:"保存",
            cancelLabel:"清除"
          });
          if (answer) {
            //保存文件
            saveFile();
          } else {
            if (vditor.value?.getValue) {
              fileContent.value = "";
              vditor.value?.setValue("");
              fileId.value = 0;
            }
          }
          await writeTextFile(cacheFileName, "", { baseDir: BaseDirectory.AppData });
        } else {
          console.log(2)
          fileContent.value = await readTextFile(cacheFileName, { baseDir: BaseDirectory.AppData });
          vditor.value?.setValue(fileContent.value);
          filePath.value = "";
          fileName.value = cacheFileName; 
          fileId.value = 0;         
        }
        vditor.value!.clearStack();
      },
    },
    {
      name: 'open',
      tipPosition: 's',
      tip: '打开文件',
      className: 'right',
      icon: '<svg width="800px" height="800px" viewBox="0 0 1024 1024" class="icon"  version="1.1" xmlns="http://www.w3.org/2000/svg"><path d="M719.8 651.8m-10 0a10 10 0 1 0 20 0 10 10 0 1 0-20 0Z" fill="#E73B37" /><path d="M512.1 64H172v896h680V385.6L512.1 64z m278.8 324.3h-280v-265l280 265zM808 916H216V108h278.6l0.2 0.2v296.2h312.9l0.2 0.2V916z" fill="#39393A" /><path d="M280.5 530h325.9v16H280.5z" fill="#39393A" /><path d="M639.5 530h90.2v16h-90.2z" fill="#E73B37" /><path d="M403.5 641.8h277v16h-277z" fill="#39393A" /><path d="M280.6 641.8h91.2v16h-91.2z" fill="#E73B37" /><path d="M279.9 753.7h326.5v16H279.9z" fill="#39393A" /><path d="M655.8 753.7h73.9v16h-73.9z" fill="#E73B37" /></svg>',
      async click () {
        const file:FileResponse[]|null = await open({
          multiple: true,
          directory: false,
        });
   
        if (file) {
          console.log(file[0].path);
          await openFile(file[0].path);
          emit('addPath', file[0].path);
        }
        vditor.value!.clearStack();
      },
    },
    "outline",

    {
      hotkey: '⌘S',
      name: 'save',
      tipPosition: 's',
      tip: '保存',
      className: 'right',
      icon: '<svg width="128" height="128" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M40.3535 14.3535C40.7441 14.7441 40.7441 15.3772 40.3535 15.7678L20.7071 35.4142C20.3166 35.8047 19.6834 35.8047 19.2929 35.4142L9.64644 25.7678C9.25591 25.3772 9.25591 24.7441 9.64644 24.3535L10.7979 23.202C11.1865 22.8135 11.8157 22.8112 12.2071 23.197L20 30.8787L37.7929 13.2025C38.1838 12.8141 38.8152 12.8152 39.2048 13.2048L40.3535 14.3535Z" fill="#EE0A24"></path></svg>',
      async click () {
        if (filePath.value) {

        } else {
          saveFile()
        }
        console.log("=====" + fileId.value);
        //上传数据
        // let count = await db.select<Array<FileData>>("select id from file_info where id = $1", [fileId.value]);
        // console.log("count:" + count.length)
        // if (count.length === 1) {
        //   await db.execute("update file_info SET content = $1 where id = $2", [vditor.value?.getValue(), fileId.value])
        // } else {
        //   fileId.value = parseInt(nanoid());
        //   await db.execute("INSERT into file_info (id, name, content, local_path, is_use) VALUES ($1, $2, $3, $4, $5)", [fileId.value, "", vditor.value?.getValue(), filePath.value, 1])
        // }

      },
    },//<svg><use xlink:href="#vditor-icon-upload"></use></svg>
    {
      name: 'upload_file',
      tipPosition: 's',
      tip: '上传',
      className: 'right',
      icon: '<svg><use xlink:href="#vditor-icon-upload"></use></svg>',
      async click () {

        if (!filePath.value) {
          alert("请先保存文件");
          return;
        }

        const files:FileResponse[] | null = await open({
          multiple: true,
          directory: false,
        });
        if (files) {
          for (let i = 0; i < files.length; i++) {
            let file = files[i];

            console.log(file.path)
            console.log(filePath.value)
            let name = getFileName(file.path)
            if (name.endsWith("jpg") || name.endsWith("png") || name.endsWith("JPG") || name.endsWith("PNG")) {
              vditor.value?.insertValue("![" + name + "](" + convertFileSrc(file.path) + ")")
            } else {
              vditor.value?.insertValue("[" + name + "](" + file.path + ")")
            }
            //保存到上传的文件
            //await invoke("upload_file", {fromFile: file.path, toPath: filePath.value});
            
          }
        }

      },
    },
    "export",
    "|",
    "preview",
    "emoji",
    "headings",
    "bold",
    "italic",
    "strike",
    "link",
    "|",
    "list",
    "ordered-list",
    "check",
    "outdent",
    "indent",
    "|",
    "quote",
    "line",
    "code",
    "inline-code",
    "|",
    "table",
    "|",
    "undo",
    "redo",
    ],
    after: () => {
      // vditor.value is a instance of Vditor now and thus can be safely used here
      vditor.value!.setValue(fileContent.value);
      let tools = document.getElementsByClassName("vditor-tooltipped");
      let toolbar = document.getElementsByClassName("vditor-toolbar");
      //vditor-toolbar__item
      let toolbar_item = document.getElementsByClassName("vditor-toolbar__item");

      if (window.innerWidth < 800) {
        toolbar.item(0)?.setAttribute('style',"padding-left:" + 0 + "px; ")
      } else {
        toolbar.item(0)?.setAttribute('style',"padding-left:" + ((window.innerWidth - 800)/2+20) + "px; ")
      }

      for (let i =0 ; i<tools.length; i++) {
        if("outline" === tools.item(i)?.getAttribute("data-type")) {
          tools.item(i)?.addEventListener("click", outlineFun)
        }
      }
      for (let i=0; i < toolbar_item.length; i++) {
        toolbar_item.item(i)?.setAttribute('style',"padding:0px")
      }
      for (let i=0; i < toolbar_item.length; i++) {
        toolbar_item.item(i)?.setAttribute('style',"padding:0px")
      }

      window.addEventListener("resize", () => {
        if (window.innerWidth < 800) {
          toolbar.item(0)?.setAttribute('style',"padding-left:" + 0 + "px; ")
        } else {
          console.log(window.innerWidth)
          console.log(window.innerWidth)
          toolbar.item(0)?.setAttribute('style',"padding-left:" + ((window.innerWidth - 800)/2+20) + "px; ")
        }
        //document.getElementById("vditor")?.setAttribute("style", "height:" + (window.innerHeight - 2).toString() + "px");
        document.getElementById("vditor")?.setAttribute("style", "height:99.5%;");
      })

      
    },
    link:{
      isOpen:false,
      click:async (bom: Element) => {
        //console.log(bom.getAttribute("href"));
        let target = bom.getAttribute("href");
        if (target) {
          if (target.startsWith("http")) {
            //window.open(target);
            await createWin({
              label: 'dev-' + autograph(target),
              title: "网络预览",
              url: target,
              resizable: false,
              alwaysOnTop: false,
            })
          } else {
            await createWin({
              label: 'dev-' + autograph(target),
              title: getFileName(bom.getAttribute("href")!),
              url: '/index.html?source=' + filePath.value + '&target=' + target,
              resizable: false,
              alwaysOnTop: false,
            })
          }
        }
      }
    },
    mode:"wysiwyg",
    ctrlEnter: (test: String) => {
      console.log(test)
    },
    input:async (value: string) => {
      
      if (fileId.value) {
        saveHadFile()
      } else {
        if (filePath.value) {
          //保存到文件
          await invoke("write_file", {path: filePath.value, fileName:fileName.value, data: value});
        } else {
          await writeTextFile(cacheFileName, value, { baseDir: BaseDirectory.AppData });
        }
      }


    },
    preview: {
      delay: 600,
      mode: "both",
      parse:(_: HTMLElement) =>{
        
      },
      transform:(html: string) => {
        return html;
      },
      theme:{
        current: "Dark",
        list: { "ant-design": "Ant Design", dark: "Dark", light: "Light", wechat: "WeChat" },
        path: "https://unpkg.com/vditor@$3.10.1/dist/css/content-theme",
      }

    },
    resize:{
      enable:true
    },
    i18n:{
      'alignCenter': '居中',
      'alignLeft': '居左',
      'alignRight': '居右',
      'alternateText': '替代文本',
      'bold': '粗体',
      'both': '编辑 & 预览',
      'check': '任务列表',
      'close': '关闭',
      'code': '代码块',
      'code-theme': '代码块主题预览',
      'column': '列',
      'comment': '评论',
      'confirm': '确定',
      'content-theme': '内容主题预览',
      'copied': '已复制',
      'copy': '复制',
      'delete-column': '删除列',
      'delete-row': '删除行',
      'devtools': '开发者工具',
      'down': '下',
      'downloadTip': '该浏览器不支持下载功能',
      'edit': '编辑',
      'edit-mode': '切换编辑模式',
      'emoji': '表情',
      'export': '导出',
      'fileTypeError': '文件类型不允许上传，请压缩后再试',
      'footnoteRef': '脚注标识',
      'fullscreen': '全屏切换',
      'generate': '生成中',
      'headings': '标题',
      'heading1': '一级标题',
      'heading2': '二级标题',
      'heading3': '三级标题',
      'heading4': '四级标题',
      'heading5': '五级标题',
      'heading6': '六级标题',
      'help': '帮助',
      'imageURL': '图片地址',
      'indent': '列表缩进',
      'info': '关于',
      'inline-code': '行内代码',
      'insert-after': '末尾插入行',
      'insert-before': '起始插入行',
      'insertColumnLeft': '在左边插入一列',
      'insertColumnRight': '在右边插入一列',
      'insertRowAbove': '在上方插入一行',
      'insertRowBelow': '在下方插入一行',
      'instantRendering': '即时渲染',
      'italic': '斜体',
      'language': '语言',
      'line': '分隔线',
      'link': '链接',
      'linkRef': '引用标识',
      'list': '无序列表',
      'more': '更多',
      'nameEmpty': '文件名不能为空',
      'ordered-list': '有序列表',
      'outdent': '列表反向缩进',
      'outline': '大纲',
      'over': '超过',
      'performanceTip': '实时预览需 ${x}ms，可点击编辑 & 预览按钮进行关闭',
      'preview': '预览',
      'quote': '引用',
      'record': '开始录音/结束录音',
      'record-tip': '该设备不支持录音功能',
      'recording': '录音中...',
      'redo': '重做',
      'remove': '删除',
      'row': '行',
      'spin': '旋转',
      'splitView': '分屏预览',
      'strike': '删除线',
      'table': '表格',
      'textIsNotEmpty': '文本（不能为空）',
      'title': '标题',
      'tooltipText': '提示文本',
      'undo': '撤销',
      'up': '上',
      'update': '更新',
      'upload': '上传图片或文件',
      'uploadError': '上传错误',
      'uploading': '上传中...',
      'wysiwyg': '所见即所得',
    }

  });
});

function outlineFun() {
  let toolbar = document.getElementsByClassName("vditor-toolbar");
  if (window.innerWidth < 800) {
    toolbar.item(0)?.setAttribute('style',"padding-left:" + 0 + "px; ")
  } else {
    toolbar.item(0)?.setAttribute('style',"padding-left:" + ((window.innerWidth - 800)/2+20) + "px; ")
  }
}

async function saveFile() {
  if (!fileId.value) {
    const path = await save({
      filters: [{
        name: 'Image',
        extensions: ['md']
      }]
    });
    if (path) {
      filePath.value = getPath(path);
      fileName.value = getFileName(path);
      emit('addPath', path);
      //保存到文件
      await invoke("write_file", {path: filePath.value, fileName:fileName.value, data: vditor.value?.getValue()}); 
    }
  } else {
    saveHadFile()
  }
}

async function saveHadFile() {
  if (fileId.value) {
    invoke("up_file_content", {fileId: fileId.value, userId:"123456", content: vditor.value?.getValue()});
  }
}




async function openFile(f_path: string) {
  console.log("打开文件地址：" + f_path);
  let rest:string = await invoke("read_file", {path: f_path});
  console.log("********" + rest);
  if (rest.indexOf("#@#error#@#_") > -1) {
    alert(rest.replace("#@#error#@#_", ""));
    rest = "";
  }
  
  fileContent.value = rest;
  vditor.value?.setValue(fileContent.value);
  filePath.value = getPath(f_path);
  fileName.value = getFileName(f_path);
}


function getPath(filePath: string) : string {
  let split = filePath.split("\\");
  let fileName = split[split.length-1];
  return filePath.replace(fileName, "");
}

function getFileName(filePath: string) : string {
  let split = filePath.split("\\");
  let fileName = split[split.length-1];
  console.log(fileName);
  return fileName;
}











</script>

<style>
.coent{
    height: 100%;
}

.vditor-toolbar {
  display: flex;
  align-items: center;
  padding-top: 1px;
  overflow-x:auto;
  overflow-y:hidden;
}

.vditor-hint {
  z-index: 1000;
  position:fixed;
}
.vditor-preview__action {
  display: none;
}

#app {
  overflow-x:hidden
}
</style>
  